package com.fount4j.generator.jdbc;

import com.fount4j.generator.config.JdbcConfig;
import com.fount4j.generator.exception.ConnectException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 根据 JDBC 配置创建数据库连接
 *
 * @author Morven 2016/12/20
 */
public class JdbcConfigConnectionFactory implements ConnectionFactory {
    private JdbcConfig jdbcConfig;

    public JdbcConfigConnectionFactory(JdbcConfig jdbcConfig) {
        this.jdbcConfig = jdbcConfig;
    }

    @Override
    public Connection getConnection() {
        try {
            Class.forName(jdbcConfig.getDriverClass());
            Properties properties = new Properties();
            properties.put("user", jdbcConfig.getUser());
            properties.put("password", jdbcConfig.getPassword());
            properties.putAll(jdbcConfig.getProperties());
            return DriverManager.getConnection(jdbcConfig.getUrl(), properties);
        } catch (ClassNotFoundException e) {
            throw new ConnectException("数据库驱动类没有找到", e);
        } catch (SQLException e) {
            throw new ConnectException("连接数据库出错", e);
        }
    }
}
